package com.cobo.common.core;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class StorageService {

    public static synchronized File getBaseDir(String name) {
        File baseConfigDir = new File(System.getProperty("user.home"), ".ktool");
        if (!baseConfigDir.exists()) {
            baseConfigDir.mkdir();
        }
        return new File(baseConfigDir.getAbsolutePath() + File.separator + name);
    }

    public static void writeByteToFile(String name, byte[] bytes) throws Exception{
        FileUtils.writeByteArrayToFile(
                StorageService.getBaseDir(name)
                , bytes);
    }

    public static byte[] readFileToByte(String name) throws Exception{
        return FileUtils.readFileToByteArray(new File(name));
    }

    public static void save(String name, List<Object> objects) throws IOException {
        FileUtils.writeStringToFile(getBaseDir(name),
                JSON.toJSONString(objects), "utf-8"
        );
    }
}
